package com.cn;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.HashMap;

@SpringBootTest
public class ChatGpt {

    @Test
    void test() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("client_id","g2Gc3yioawNxXXArsDI1suWw")
                .add("client_secret","6T2a6OlG6AV7labtuwEQTmoav0edPLG4")
                .add("grant_type","client_credentials")
                .build();

        Request request = new Request.Builder()
                .addHeader("content-type", "application/json")
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .post(requestBody)
                .build();

        String result = okHttpClient.newCall(request).execute().body().string();
        JSONObject jsonObject = JSONArray.parseObject(result);
        String string = jsonObject.getString("access_token");

        ss(string);
    }

    void ss(String s) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();

        HashMap<String, String> paramMapRole = new HashMap<>();
        paramMapRole.put("role","user");
        paramMapRole.put("content","你的名字");
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("messages",paramMapRole.toString());

        Request request = new Request.Builder()
                .addHeader("content-type", "application/json")
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token="+s)
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"),paramMap.toString()))
                .build();

        String result = okHttpClient.newCall(request).execute().body().string();
        System.out.println(result);
    }

}
